package com.itboye.sunsun.shop.ui;

import java.util.ArrayList;
import java.util.List;

import com.itboye.sunsun.R;
import com.itboye.sunsun.adapter.DianPuTuiJianAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.DianPuTuiJianBean;
import com.itboye.sunsun.beans.DianPuTuiJianBean.GoodsItemBean;
import com.itboye.sunsun.beans.FiveImageBean;
import com.itboye.sunsun.beans.GoodBean;
import com.itboye.sunsun.beans.GoodsDetailBean;
import com.itboye.sunsun.beans.FiveImageBean.PicturesBean;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.custome.CarouselView;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.personsetting.ui.SetEmailActivity;
import com.itboye.sunsun.shop.ui.fragment.JiaRuGouWuCheDialog;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.test.ImageUrls;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.DebugToast;
import com.itboye.sunsun.utils.DensityUtil;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.XImageLoader;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsun.wxapi.WXEntryActivity;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.LayoutParams;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class GoodDetailActivity extends BaseActivity {

	// private static final String DETAIL_URL = "http://baidu.com";

	CarouselView lunbo;
	TextView name;
	View share;
	TextView price;
	TextView oldPrice;
	RelativeLayout fenlei;
	TextView xiaoliang;
	ViewGroup shoucang;
	View jiaruGouWuChe;
	View liJiGouMai;
	// RelativeLayout fenlei;
	// TextView tuwen;
	// TextView dianpu;
	// ViewPager viewPager;
	//
	View gouwuche;
	XListView xlistview;
	BaseAdapter tuijianAdapter;
	WebAdapter webAdapter;
	String goodId;
	// String guanId;
	GoodsDetailBean goodsDetailBeans;
	List<GoodsItemBean> tuijianDataList = new ArrayList<GoodsItemBean>();
	private ShareFragment shareFragment;
	protected String goodsName;

	private String imgUrl;

	protected void onCreate(android.os.Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.activity_good_detail);
		showProgressDialog("获取数据中,请稍后", true);
		Intent intent = getIntent();
		goodId = intent.getStringExtra("what");
		imgUrl=intent.getStringExtra("imgUrl");
		// goodId="88";//"114" 测试 暂时设为这两个值
		// DebugToast.show("click: "+goodId, 1);
		// guanId=intent.getStringExtra("guan");
		// DebugToast.show("click: "+goodId+"\n\n" , 1);

		// 注册广播
		IntentFilter intentFilterEmail = new IntentFilter(
				WXEntryActivity.DISMISSFRAGMENT);
		this.registerReceiver(emailBroadcastReceiver, intentFilterEmail);
		initViews();

		getData();

		getDianPuTuiJian();
	}

	static {
//		PlatformConfig.setWeixin("wxa30658c4f4f6bbf4",
//				"69c4d761d4a0801bba64bef359bbf0b2");
		// PlatformConfig.setQQZone("1104665874", "rsZV0GmonT5OEZQo");
	}

	private void getDianPuTuiJian() {

		MyJsonRequest<DianPuTuiJianBean> request = new MyJsonRequest.Builder<DianPuTuiJianBean>()
				.apiVer("100").typeKey("BY_Product_queryByGroup")
				.param("group_id", "16")
				// .param("cate_id", guanId)
				.requestListener(new XRequestListener<DianPuTuiJianBean>() {

					@Override
					public void onResponse(DianPuTuiJianBean arg0) {
						if (arg0.getList() != null) {
							tuijianDataList.clear();
							tuijianDataList.addAll(arg0.getList());
							tuijianAdapter.notifyDataSetChanged();
						}
						xlistview.stopRefresh();
						try {

							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopRefresh();
						try {

							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private void getData() {
		String uid = (String) SPUtils.get(getApplicationContext(), null,
				SPContants.USER_ID, "");
		MyJsonRequest<GoodsDetailBean> request = new MyJsonRequest.Builder<GoodsDetailBean>()
				.apiVer("100").typeKey("BY_Product_detail").param("id", goodId)
				.param("uid", uid)
				.requestListener(new XRequestListener<GoodsDetailBean>() {

					@Override
					public void onResponse(GoodsDetailBean detailBean) {
						goodsDetailBeans = detailBean;
						List<ImageView> imageViews = new ArrayList<ImageView>();
						for (String url : detailBean.getImgs()) {
							ImageView imageView = new ImageView(
									getApplicationContext());
							imageView.setScaleType(ScaleType.CENTER_CROP);
							XImageLoader.load(url, imageView);
							imageViews.add(imageView);
						}
						lunbo.setImageBitmaps(imageViews);
						goodsName = detailBean.getName();
						name.setText(detailBean.getName());
						price.setText("￥" + detailBean.getMinPrice());
						oldPrice.setText("￥" + detailBean.getMinOriPrice());
						xiaoliang.setText("销量：" + detailBean.getTotalSales());
						if (detailBean.getFavorite() == 1) {
							((ImageView) shoucang.getChildAt(0))
									.setImageResource(R.drawable.ic_yishoucang);
							shoucang.setTag("1");
						} else {
							shoucang.setTag("0");
						}

						jiaruGouWuChe.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {

								LoginController.onAddShopCarClick(
										GoodDetailActivity.this, null);

							}

						});

						liJiGouMai.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								LoginController.onBuyClick(
										GoodDetailActivity.this, null);
							}

						});
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {

					}
				}).build();

		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void onBuyRightClick() {
		new JiaRuGouWuCheDialog(goodsDetailBeans, true).show(
				getSupportFragmentManager(), "");
	}

	public void onJiaruGouwucheClick() {
		new JiaRuGouWuCheDialog(goodsDetailBeans, false).show(
				getSupportFragmentManager(), "");
	}

	@SuppressLint("NewApi")
	private void initViews() {
		View headerView = getLayoutInflater().inflate(
				R.layout.item_goods_detail_headerview, xlistview, false);

		lunbo = (CarouselView) headerView.findViewById(R.id.lunbo);
		fenlei = (RelativeLayout) headerView.findViewById(R.id.fenlei);

		int width = DensityUtil.screenWidth();
		lunbo.setLayoutParams(new LinearLayout.LayoutParams(width, width));
		name = (TextView) headerView.findViewById(R.id.name);

		share = headerView.findViewById(R.id.share);
		share.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// onShareClick();
				LoginController
						.onGoodsShareClick(GoodDetailActivity.this, null);
			}
		});
		fenlei.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginController.onBuyClick(GoodDetailActivity.this, null);

			}
		});
		oldPrice = (TextView) headerView.findViewById(R.id.oldPrice);
		price = (TextView) headerView.findViewById(R.id.price);
		xiaoliang = (TextView) headerView.findViewById(R.id.xiaoliang);

		xlistview.addHeaderView(headerView);
		tuijianAdapter = new DianPuTuiJianAdapter(tuijianDataList, this);
		webAdapter = new WebAdapter();
		xlistview.setAdapter(webAdapter);

		final TextView tuwen = (TextView) headerView.findViewById(R.id.tuwen);
		final TextView dianpu = (TextView) headerView.findViewById(R.id.dianpu);

		final View tuwenUnderLine = headerView
				.findViewById(R.id.tuwenUnderLine);
		final View dianpuUnderLine = headerView
				.findViewById(R.id.dianpuUnderLine);

		tuwen.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tuwen.setTextColor(getResources().getColor(R.color.orange));

				tuwenUnderLine.setVisibility(View.VISIBLE);

				dianpu.setTextColor(Color.parseColor("#7a7a7a"));
				dianpuUnderLine.setVisibility(View.INVISIBLE);
				xlistview.setAdapter(webAdapter);
				lunbo.start();

			}
		});

		dianpu.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				tuwen.setTextColor(Color.parseColor("#7a7a7a"));
				tuwenUnderLine.setVisibility(View.INVISIBLE);

				dianpu.setTextColor(getResources().getColor(R.color.orange));
				dianpuUnderLine.setVisibility(View.VISIBLE);
				xlistview.setAdapter(tuijianAdapter);
				lunbo.start();
			}
		});

		findViewById(R.id.back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();
			}
		});

		findViewById(R.id.backToTop).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				xlistview.smoothScrollToPosition(0);
			}
		});

		gouwuche.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginController.onShopCarClick(GoodDetailActivity.this, null);
			}
		});

		findViewById(R.id.shangcheng).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				startActivity(new Intent(getApplicationContext(),
						AllShopActivity.class));
			}
		});

		findViewById(R.id.kefu).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginController.onShopCustomerServiceClick(
						GoodDetailActivity.this, goodId);
			}
		});

		findViewById(R.id.more).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginController
						.onShopMoreClick(GoodDetailActivity.this, goodId);
			}
		});
		shoucang.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				// onCollectClick(v);
				LoginController.onGoodsCollectClick(GoodDetailActivity.this, v);
				// ((ImageView)shoucang.getChildAt(0)).setImageResource(R.drawable.ic_yishoucang);
			}
		});

		xlistview.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				getDianPuTuiJian();
			}

			@Override
			public void onLoadMore() {

			}
		});

	}

	public void onShareClick() {
		shareFragment = new ShareFragment();
		Bundle bundle = new Bundle();
		bundle.putString("id", goodId);
		bundle.putString("goodsName", goodsName);
		bundle.putString("imgUrl", imgUrl);
		shareFragment.setArguments(bundle);
		shareFragment.show(getSupportFragmentManager(), null);
	}

	private class WebAdapter extends BaseAdapter {
		WebView webview;

		public WebAdapter() {

			webview = new WebView(GoodDetailActivity.this);
			webview.getSettings().setJavaScriptEnabled(true);

			webview.setWebViewClient(new WebViewClient() {
				@Override
				public boolean shouldOverrideUrlLoading(WebView view, String url) {
					view.loadUrl(url);
					return true;
				}
			});

			webview.loadUrl(NetPublicConstant.secondUrl+"/Webview/Product/detail?id="
					+ goodId);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			return webview;
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		@Override
		public Object getItem(int position) {

			return null;
		}

		@Override
		public int getCount() {

			return 1;
		}
	}

	public void onCollectClick(final View v) {
		if (v.getTag() == null) {
			return;
		}
		v.setEnabled(false);
		if (v.getTag().equals("1")) {
			v.setTag("0");
		} else {
			v.setTag("1");
		}
		String uid = (String) SPUtils.get(getApplicationContext(), null,
				SPContants.USER_ID, "");
		MyJsonRequest<String> request = new MyJsonRequest.Builder<String>()
				.apiVer("100").typeKey("BY_Product_favorites")
				.param("product_id", goodId).param("uid", uid)
				.param("favorite_value", (String) v.getTag())
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String arg0) {

						if (v.getTag().equals("1")) {
							((ImageView) shoucang.getChildAt(0))
									.setImageResource(R.drawable.ic_yishoucang);
						} else {
							((ImageView) shoucang.getChildAt(0))
									.setImageResource(R.drawable.ic_shoucang);
						}
						v.setEnabled(true);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {

						if (v.getTag().equals("1")) {
							v.setTag("0");
							((ImageView) shoucang.getChildAt(0))
									.setImageResource(R.drawable.ic_shoucang);
						} else {
							v.setTag("1");
							((ImageView) shoucang.getChildAt(0))
									.setImageResource(R.drawable.ic_yishoucang);
						}
						v.setEnabled(true);
					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

//	private UMShareListener umShareListener = new UMShareListener() {
//		@Override
//		public void onResult(SHARE_MEDIA platform) {
//			Toast.makeText(GoodDetailActivity.this, platform + " 分享成功啦",
//					Toast.LENGTH_SHORT).show();
//		}
//
//		@Override
//		public void onError(SHARE_MEDIA platform, Throwable t) {
//			Toast.makeText(GoodDetailActivity.this, platform + " 分享失败啦",
//					Toast.LENGTH_SHORT).show();
//		}
//
//		@Override
//		public void onCancel(SHARE_MEDIA platform) {
//			Toast.makeText(GoodDetailActivity.this, platform + " 分享取消了",
//					Toast.LENGTH_SHORT).show();
//		}
//	};

//	private ShareBoardlistener shareBoardlistener = new ShareBoardlistener() {
//
//		@Override
//		public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
//			new ShareAction(GoodDetailActivity.this).setPlatform(share_media)
//					.setCallback(umShareListener).withText("多平台分享").share();
//		}
//	};

//	@Override
//	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//		super.onActivityResult(requestCode, resultCode, data);
//		/** attention to this below ,must add this **/
//		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
//	}

	BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {

			shareFragment.dismiss();
		};
	};

	protected void onDestroy() {
		unregisterReceiver(emailBroadcastReceiver);
		super.onDestroy();
	};

}
